package chapter2;

/**
 * 个体
 */
public class Individual {
	//染色体 int数组
    private int[] chromosome;
    //个体适应度
    private double fitness = -1;

    /**
     * 用int数组初始化染色体
     *
     * @param chromosome 染色体int数组
     */
    public Individual(int[] chromosome) {
        this.chromosome = chromosome;
    }

    /**
     * 初始化指定个数的染色体
     *
     * @param chromosomeLength 指定染色体长度
     */
    public Individual(int chromosomeLength) {
        this.chromosome = new int[chromosomeLength];
        for (int gene = 0; gene < chromosomeLength; gene++) {
            // Math.random()产生0~1之间的数，>0.5 设置基因0，<=0.5设置基因1
            if (0.5 < Math.random()) {
                this.setGene(gene, 1);
            } else {
                this.setGene(gene, 0);
            }
        }
    }


    public int[] getChromosome() {
        return this.chromosome;
    }

    /**
     * 获取染色体长度
     *
     * @return 染色体长度
     */
    public int getChromosomeLength() {
        return this.chromosome.length;
    }

    /**
     * 设置某个位置的基因值
     *
     * @param gene
     * @param offset
     * @return gene
     */
    public void setGene(int offset, int gene) {
        this.chromosome[offset] = gene;
    }

    /**
     * 获取指定位置的基因
     *
     * @param offset
     * @return gene
     */
    public int getGene(int offset) {
        return this.chromosome[offset];
    }

    /**
     * 设置个体适应度
     *
     * @param fitness
     */
    public void setFitness(double fitness) {
        this.fitness = fitness;
    }

    /**
     * 获取个体适应度
     *
     * @return 个体适应度
     */
    public double getFitness() {
        return this.fitness;
    }


    /**
     * 改写toString方法，打印基因值
     *
     * @return 染色体基因值
     */
    public String toString() {
        String output = "";
        for (int gene = 0; gene < this.chromosome.length; gene++) {
            output += this.chromosome[gene];
        }
        return output;
    }
}
